<template>
  <div class="shop"
    v-loading="loading">
    <div class="store_line"></div>
    <div class="base_infoset">商品基础设置</div>
    <div class="triangle_right"></div>
    <el-form :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm">
      <el-form-item label="关联分类:"
        prop="guanlian_cate">
        <el-select style="width:180px;"
          size='small'
          v-model="form.guanlian_cate"
          filterable
          class="select"
          placeholder="请选择关联的分类">
          <el-option v-for="item in categoryList"
            :key="item.id"
            :label="item.cate_name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标题:"
        prop="title">
        <el-input v-model="form.title"
          style="width:40%;"
          size='small'></el-input>
        <div class="base_title">原标题：{{form.title}}</div>
      </el-form-item>

      <el-form-item label='副标题:'
        prop='sub_title'>
        <el-input v-model="form.sub_title"
          style="width:40%;"
          size='small'></el-input>
      </el-form-item>

      <el-form-item label='商品图片:'
        prop='img_arr'>
        <div class="sku_pic">
          <div v-for='(item,index) in form.img_arr'
            :key="index"
            class="main_sku">
            <img style="width:160px;height:160px;"
              class="sku_pic_margin"
              :src="item? item : errorImg"
              alt />
            <p v-if='index ==0'
              class="main_img">商品主图</p>
            <p v-else
              class="other_img main_img">商品轮播图</p>
          </div>
        </div>
      </el-form-item>

      <el-form-item label='展示排序:'
        prop='order'>
        <el-input v-model="form.order_sort"
          type='number'
          style="width:40%;"
          size='small'
          placeholder='1~4999'></el-input>
        <span class="sub_note">数值越大排序越靠前</span>
      </el-form-item>
    </el-form>

    <div class="add_info">
      <div class="store_line"></div>
      <div class="base_infoset base_addset">商品加润/抵扣设置</div>
      <div class="triangle_right add_right"></div>

      <el-form :model="addform"
        label-width="100px"
        class="demo-ruleForm">
        <el-form-item label='商品加润比:'
          prop='profit_set_rate'>
          <el-input v-model="addform.profit_set_rate"
            type='number'
            style="width:40%;"
            size='small'
            @change="pricerateSet">
            <p class="note_back"
              slot="suffix">%</p>
          </el-input>
          <span class="sub_note">加润比是在成本价的基础根据加润的比例售价，例如加润比100%，则售价是成本价的2倍</span>
        </el-form-item>

        <el-form-item label='红包抵扣:'
          prop='red_packet_discount_price'>
          <el-input v-model="addform.red_packet_discount_price"
            type='number'
            style="width:40%;"
            @change="profitChangeDiscount"
            size='small'>
            <p class="note_back"
              slot="suffix">元</p>
          </el-input>
          <span class="sub_note">设置红包可以抵扣的金额</span>
        </el-form-item>

        <el-form-item label='包邮件数设置:'
          prop='free_freight_num'>
          <el-input v-model="addform.free_freight_num"
            type='number'
            style="width:40%;"
            size='small'
            @change="pricerateSet">
            <p class="note_back"
              slot="suffix">件</p>
          </el-input>
          <span class="sub_note">设置包邮件数，是指n件起包邮，未达到包邮条件的需要增收运费，未设置默认为0，表示不包邮</span>
        </el-form-item>

        <el-form-item label="运费模板设置:"
          >
          <el-select style="width:40%;"
            size='small'
            v-model="addform.freightTemplates"
            filterable
            class="select"
            placeholder="请选择运费模板设置">
            <el-option v-for="item in freightTemplates"
              :key="item.id"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="sku_info">
      <div class="store_line"></div>
      <div class="base_infoset ">商品参数设置</div>
      <div class="triangle_right"></div>

      <div class="table">
        <el-table border
          :data="tableData"
          style="width:100%"
          max-height="600"
          :cell-style="tc"
          :header-cell-style="tccolor">

          <el-table-column label='SKU编号'
            prop='sku_id'></el-table-column>
          <el-table-column v-for="(item,index) in attr_name_arr"
            :label='item'
            :key='index'>
            <template slot-scope="scope">
              <p>{{scope.row.attr_value_arr[index]}}</p>
            </template>
          </el-table-column>
          <el-table-column label='商品库存'
            prop='stock'></el-table-column>
          <el-table-column label='虚拟销量'
            prop='fictitious_sale_count'
            width='140'>
            <template slot-scope="scope">
              <!-- <div class="rectangle">{{scope.row.fictitious_sale_count}}</div> -->
              <el-input-number size='mini'
                style="width:100px;"
                v-model="scope.row.fictitious_sale_count"
                :min="0"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label='库存预警'
            prop='warning_stock'
            width='140'>
            <template slot-scope="scope">
              <el-input-number size='mini'
                style="width:100px;"
                v-model="scope.row.warning_stock"
                :min="0"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label='供货成本价'
            prop='supply_price'>
          </el-table-column>
          <el-table-column label='运费成本'
            prop='supply_freight_price'>
          </el-table-column>
          <el-table-column label='* 销售价格'
            width='140'>
            <template slot-scope="scope">
              <!-- <div class="rectangle">¥{{scope.row.sale_price}}</div> -->
              <el-input v-model="scope.row.sale_price"
                size='mini'
                style='width:100px'
                type='number'
                @change="saleprice(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label='* 红包抵扣'
            width='140'>
            <template slot-scope="scope">
              <!-- <div class="rectangle">{{scope.row.red_packet_discount_price}}</div> -->
              <el-input v-model="scope.row.red_packet_discount_price"
                size='mini'
                style='width:100px'
                type='number'
                @change="discountprice(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label='实付价'>
            <template slot-scope="scope">
              {{scope.row.actual_price}}
            </template>
          </el-table-column>
          <el-table-column label='商品利润'
            prop='profit'></el-table-column>
          <el-table-column label='操作'
            fixed='right'>
            <!--返回1说明该sku当前是展示的，0说明该sku当前是隐藏的-->
            <template slot-scope="scope">
              <el-button size='mini'
                type='danager'
                v-if='scope.row.is_display==1'
                @click="hideSku(scope.row,1)">隐藏</el-button>
              <el-button size='mini'
                type='danager'
                v-if='scope.row.is_display==0'
                @click="hideSku(scope.row,2)">展示</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="certain_add">
      <el-button size='small'
        @click="cancelAdd">取消</el-button>
      <el-button type='primary'
        size='small'
        v-if='type==1'
        @click="addShopToStore">保存入库</el-button>
      <el-button type='primary'
        size='small'
        v-if='type==2'
        @click="addShopToStore">保存修改</el-button>
    </div>
  </div>
</template>

<script>
import {  supplyProductSkuList,
  supplyProductImgList,
  supplyproductCateList,
  freightTemplateList,
  selfproductDetail,
  selfproductUpdate} from "@/api/autarky";
export default {

  data () {
    return {
      type: 0,
      product_no: '',
      categoryList: [],
      freightTemplates: [],
      form: {
        guanlian_cate: '',
        title: '',
        sub_title: '',
        img_arr: [],
        order_sort: 0,
      },
      addform: {
        profit_set_rate: 0,
        red_packet_discount_price: 0,
        freightTemplates:'',
        free_freight_num:0,
      },
      //sku相关
      tableData: [],
      attr_name_arr: [],
      rules: {
        guanlian_cate: [
          { required: true, message: '请选择关联分类', trigger: 'blur' },
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 55, message: '长度不能少于一个字符', trigger: 'blur' }
        ],
        sub_title: [
          { required: true, message: '请输入副标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度不能少于一个字符', trigger: 'blur' }
        ],
        img_arr: [{ required: true, message: '请选择商品图片', trigger: 'blur' },],
        order_sort: [
          { required: true, message: '请选择展示排序', trigger: 'blur' },
        ],
      },
      loading: false
    }
  },
  mounted () {
    this.product_no = this.$route.query.product_no
    this.type = this.$route.query.type
    this.form.title = this.$route.query.title
    if (this.product_no) {
       this.getsupplyproductCateListData()
      this.getselfproductDetailData()
      this.getsupplyProductImgListData()
      this.getsupplyProductSkuListData()
      this.listFreightTemplates()
    }
  },
  methods: {
    //取消
    cancelAdd () {
      this.$router.push({ path: './supplyChainStore' })
    },
    //保存入库
    addShopToStore () {
      this.getselfproductUpdateData()
    },
    //展示。。隐藏
    hideSku (skuInfo, type) {
      if (type == 1) {
        if (skuInfo) {
          skuInfo.is_display = 0
        }
      } else {
        skuInfo.is_display = 1
      }
    },
    profitChangeDiscount () {
      if (this.tableData.length > 0) {
        this.tableData.map(obj => {
          obj.red_packet_discount_price = this.addform.red_packet_discount_price
          obj.actual_price = (obj.sale_price - obj.red_packet_discount_price).toFixed(2)
          if (obj.actual_price < 0) {
            obj.actual_price = 0
          }
          obj.profit = (obj.actual_price -obj.supply_price).toFixed(2)
        })
      }
    },
    pricerateSet () {
      if (this.tableData.length > 0) {
        this.tableData.map(obj => {
          obj.sale_price = (obj.supply_price * (1 + this.addform.profit_set_rate / 100)).toFixed(2)
          obj.actual_price = (obj.sale_price - obj.red_packet_discount_price).toFixed(2)
          if (obj.actual_price < 0) {
            obj.actual_price = 0
          }
          obj.profit = (obj.actual_price -obj.supply_price).toFixed(2)
        })
      }
    },
    //red_packet_discount_price actual_price sale_price
    saleprice (data) {
      data.actual_price = (data.sale_price - data.red_packet_discount_price).toFixed(2)
      if (data.actual_price < 0) {
        data.actual_price = 0
      }
      data.profit = (data.actual_price -data.supply_price).toFixed(2)
    },
    discountprice (data) {
      data.actual_price = (data.sale_price - data.red_packet_discount_price).toFixed(2)
      if (data.actual_price < 0) {
        data.actual_price = 0
      }
      data.profit = (data.actual_price -data.supply_price).toFixed(2)
    },
    //获取商品详情
    async getselfproductDetailData () {
      let res = await selfproductDetail(this.product_no)
      if (res.code === 10000) {
        if(res.data.title){
          this.form.title = res.data.title
        }
        this.form.sub_title = res.data.sub_title
        this.form.order_sort = res.data.order_sort
        this.form.guanlian_cate = res.data.cate_id
        this.addform.profit_set_rate = res.data.profit_set_rate
        this.addform.red_packet_discount_price = res.data.red_packet_discount_price
        this.addform.freightTemplates = res.data.freight_template_id
        this.addform.free_freight_num = res.data.free_freight_num
      } else {
        this.$message.error(res.message)
      }
    },
    //查看sku图片
    async getsupplyProductImgListData () {
      let res = await supplyProductImgList(this.product_no)
      if (res.code === 10000) {
        this.form.img_arr = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    async getsupplyProductSkuListData () {
      let res = await supplyProductSkuList(this.product_no)
      if (res.code === 10000) {
        this.attr_name_arr = res.data.attr_name_arr
        this.tableData = res.data.list
      } else {
        this.$message.error(res.error)
      }
    },
    //获取分类列表
    async getsupplyproductCateListData () {
      var url = "id=&is_enable=1&cate_name="
      let res = await supplyproductCateList(url)
      if (res.code === 10000) {
        this.categoryList = res.data.data
      } else {
        this.$message.error(res.message)
      }
    },

    //获取运费模板
    async listFreightTemplates () {
      let res = await freightTemplateList()
      if (res.code === 10000) {
        this.freightTemplates = res.data
      } else {
        this.$message.error(res.message)
      }
    },

    //更新详情
    async getselfproductUpdateData () {
      if(!this.form.sub_title){
        this.$message.error('副标题不能为空')
        return
      }
      if(!this.addform.freightTemplates){
        this.$message.error('运费模版设置必选')
        return
      }
      if(!this.addform.profit_set_rate){
        this.addform.profit_set_rate = 0
      }
      if(!this.addform.red_packet_discount_price){
        this.addform.red_packet_discount_price = 0
      }
       if(!this.addform.free_freight_num){
        this.addform.free_freight_num = 0
      }
     this.loading = true
       var data = {        
        cate_id: this.form.guanlian_cate,
        title: this.form.title,
        sub_title: this.form.sub_title,
        order_sort: this.form.order_sort,
        profit_set_rate: this.addform.profit_set_rate,
        red_packet_discount_price: this.addform.red_packet_discount_price,
        freight_template_id: this.addform.freightTemplates,
        free_freight_num: this.addform.free_freight_num
      }
      if(this.tableData.length >0 ){
      //   this.tableData.forEach(function (obj, index) {
      //     var dic = {}
      //   Object.keys(obj).map(item => {
         
      //     var str = 'sku_list[' + index + '][' + item + ']'
      //     dic[str] = obj[item]
      //   })
      //   skuArr.push(dic)
      
      // })
        data['sku_list'] = JSON.stringify(this.tableData)
      }
      let res = await selfproductUpdate(this.product_no, data)
      if (res.code === 10000) {
        this.loading = false
        this.$message.success(res.message)
        if (this.type == 1) {
          this.$router.push({
            path: './addshopTostore'          })
        } else {
          this.$router.push({
            path: './localstore'          })
        }
      } else {
        this.loading = false
        this.$message.error(res.message)
      }
    },
    //获取商品图片
    getFile (file) {
      if (file.files && file.files.length && file.name == 'storeShop_pic_list"') {
        this.img_url = file.files.map(obj => obj.url)
      }
    },

    tc () {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor () {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
  }
}
</script>

<style lang="scss" scoped>
.shop {
  position: relative;
  .store_line {
    background-color: #e5e5e5;
    height: 1px;
    margin-top: 20px;
    width: 100%;
  }
  .base_infoset {
    background-color: #f4222d;
    color: #ffffff;
    font-size: 18px;
    height: 30px;
    line-height: 30px;
    margin-left: 20px;
    padding: 0px 12px;
    width: 140px;
  }

  .base_addset {
    width: 180px;
  }
  .triangle_right {
    position: absolute;
    top: 1px;
    left: 160px;
    width: 0px;
    height: 0px;
    border: 15px solid transparent;
    border-left: 15px solid #f4222d;
  }

  .add_info {
    position: relative;
    .add_right {
      left: 200px;
    }
  }
  .sku_info {
    position: relative;
    .table {
      padding: 0 20px;
      margin-top: 20px;

      .rectangle {
        border: 1px solid #e5e5e5;
      }
    }
  }

  .demo-ruleForm {
    position: relative;
    margin: 15px 0px;
    .base_title {
      font-size: 12px;
      color: #333333;
    }
    .sub_note {
      margin-left: 12px;
      font-size: 14px;
      color: #666666;
    }
  }
  .certain_add {
    text-align: center;
    margin-top: 20px;
  }
  .sku_pic {
    padding: 12px 20px;
    .sku_pic_margin {
      margin: 12px 12px;
    }
    .main_sku {
      position: relative;
      float: left;
    }
    .main_img {
      position: absolute;
      bottom: 0;
      left: 12px;
      background-color: #f5f5f5;
      color: #f4222d;
      text-align: center;
      font-size: 14px;
      line-height: 30px;
      height: 30px;
      width: 160px;
    }
    .other_img {
      color: rgb(71, 255, 47);
    }
  }
}
</style>